package com.learn.redis.config;

import com.learn.redis.lock.LockService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import reactor.util.annotation.NonNull;

import java.util.HashMap;
import java.util.Map;

/**
 * @author PC
 * 项目启动时的一些初始化操作
 */
@Component
public class ServiceInitConfiguration implements ApplicationContextAware {

    private final static Logger LOGGER = LoggerFactory.getLogger(ServiceInitConfiguration.class);

    private final Map<String, LockService> LOCK_SERVICE_MAP = new HashMap<>();

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        //初始化lockService
        this.initLockService(applicationContext);
    }

    /**
     * 初始化lockService
     *
     * @param applicationContext 上下文
     */
    private void initLockService(ApplicationContext applicationContext) {
        LOGGER.info("start init lockService");
        Map<String, LockService> lockServiceMap = applicationContext.getBeansOfType(LockService.class);
        for (Map.Entry<String, LockService> lockServiceEntry : lockServiceMap.entrySet()) {
            String lockType = lockServiceEntry.getValue().lockType();
            LOCK_SERVICE_MAP.put(lockType, lockServiceEntry.getValue());
            LOGGER.info("initLockService>>>>>>>lockType:{},className:{}", lockType, lockServiceEntry.getValue().getClass().getName());
        }
    }

    /**
     * 获取lockServiceMap
     *
     * @return lockService map
     */
    public Map<String, LockService> getLockServiceMap() {
        return LOCK_SERVICE_MAP;
    }
}
